<template>
  <PageModal
    :show="show"
    :title="$t('FavoriteManage.Title')"
    :page-style="pageStyle"
    :footer-size="footerSize"
    :footer-style="footerStyle"
    @back="closeModal"
  >
    <view class="container">
      <view class="recommendedChefs" v-for="(favorite, index) in favoriteList" :key="index">
        <movable-area class="movable-area">
          <movable-view class="movable-view" direction="horizontal">
            <view
              class="touch-item"
              :class="{ 'touch-move-active': favorite.isTouchMove }"
              @touchstart="touchstart"
              @touchmove="touchmove($event, index)"
            >
              <view class="content" @click="updateFavorite(favorite)">
                <view class="content-box">
                  <view class="favorite-name">{{ favorite.name }}</view>
                </view>
                <image class="favorite-operate" src="/static/ic_back.png"></image>
              </view>
              <view class="del" @click="deleteFavorite(index)">
                <view>{{ $t('FavoriteManage.Delete.Button') }}</view>
              </view>
            </view>
          </movable-view>
        </movable-area>
      </view>
    </view>

    <template #footer>
      <view class="btn" @click="jumpAddFavorite">{{ $t('FavoriteManage.AddFavorite.Button') }}</view>
    </template>
  </PageModal>
</template>

<script setup lang="ts">
import type { CSSProperties } from 'vue'
import { footerStyle, footerSize } from '@/layout/appliance/style'
import { actionDebounce } from '@/utils/mpHelper'
import { useI18n } from 'vue-i18n'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import { cloneDeep } from 'lodash'
import { selectProgram, setSetting, type ApplianceProgram } from '@/api/appliance'
import PageModal from '@/common/pageModal.vue'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'

export type NewFavoriteProgramsType = ApplianceProgram.Scope & { isTouchMove: boolean }

const pageStyle: CSSProperties = {
  backgroundColor: '#f4f4f4',
}
const i18n = useI18n()
const SettingPrefix = 'BSH.Common.Setting.Favorite'
const ProgramPrefix = 'BSH.Common.Program.Favorite.'
const SettingOff = 'BSH.Common.EnumType.Favorite.Functionality.Off'

const props = defineProps<{
  show: boolean
  control: BaseController.Control
}>()

const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
  (e: 'add-favorite', addFavoriteVisible: boolean): void
  (e: 'update-favorite'): void
}>()

const startX = ref(0)
const startY = ref(0)
const favoriteList = ref<NewFavoriteProgramsType[]>([])
const settgings = computed(() => props.control.store._datasource.settings)
const haId = computed(() => props.control.store._datasource.haId)

watch(
  () => props.show,
  (show) => {
    if (show) {
      getFavoriteList()
    }
  }
)
watch(
  () => props.control.store.favoriteProgramsList,
  () => getFavoriteList()
)
/**
 * 获取收藏列表
 */
function getFavoriteList() {
  let newFavoriteList = cloneDeep(props.control.store.favoriteProgramsList) || []

  favoriteList.value = newFavoriteList.map((favorite) => {
    settgings.value.forEach((setting) => {})
    return {
      ...favorite,
      isTouchMove: false,
    }
  })
}

function closeModal() {
  emit('update:show', false)
  emit('close')
}

/**
 * 删除收藏
 * @param index
 */
async function deleteFavorite(index: number) {
  let res: any = null
  try {
    uni.showLoading({
      title: i18n.t('APP.Common.Loading.Text'),
      mask: true,
    })
    const keyIndex = favoriteList.value[index].key?.replace(ProgramPrefix, '')

    const key = `${SettingPrefix}.${keyIndex}.Functionality`
    res = await setSetting(haId.value, key, SettingOff)

    favoriteList.value.splice(index, 1)
    uni.hideLoading()
    uni.showToast({
      title: i18n.t('APP.Common.DeleteSucess.Text'),
      icon: 'success',
    })
  } catch (error) {
    res = error
    uni.showToast({
      title: i18n.t('APP.Common.DeleteFail.Text'),
      icon: 'error',
    })
  } finally {
    safeTrack(() => {
      const trackData = favoriteList.value[index]
      trackEvent(
        'delete_favorite_program',
        {
          program_key: trackData.baseProgramKey,
          program_name: trackData.name,
          successOrNot: 'code' in res ? res.code == 0 : true,
          error_code: 'code' in res ? res.code : -1,
          response_msg: 'msg' in res ? res.msg : 'unknow',
        },
        TrackType.ApplianceDetail,
        'FavoriteManage.Delete.Button'
      )
    })
  }
}

/**
 * 更新收藏程序
 */
const activeProgramKey = computed(() => props.control.store.currentProgramKey)
const updateFavorite = actionDebounce({
  loadingText: i18n.t('APP.Common.Jumping.Text'),
  call: async (program: NewFavoriteProgramsType) => {
    if (program.key === activeProgramKey.value) {
      emit('update-favorite')
      return
    }
    await selectProgram(props.control.store._datasource.haId, program.key)
    emit('update-favorite')
  },
})

/**
 * 打开添加收藏页面
 */
function jumpAddFavorite() {
  emit('update:show', false)
  emit('add-favorite', true)
}
function touchstart(e: TouchEvent) {
  startX.value = e.changedTouches[0].pageX
  startY.value = e.changedTouches[0].pageY
}
function touchmove(e: TouchEvent, index: number) {
  const pageX = e.changedTouches[0].pageX //结束时X坐标
  const pageY = e.changedTouches[0].pageY //结束时Y坐标
  const newStartX = startX.value //开始时X坐标
  const newStartY = startY.value //开始时Y坐标
  // 获取华东角度
  const angles: number = angle(
    {
      X: newStartX,
      Y: newStartY,
    },
    {
      X: pageX,
      Y: pageY,
    }
  )
  favoriteList.value.forEach((item, i) => {
    if (angles > 30) {
      return
    }
    if (i == index) {
      if (startX.value < pageX) {
        //右滑
        item.isTouchMove = false
      } else {
        //左滑
        item.isTouchMove = true
      }
    }
  })
}
function angle(start: { X: number; Y: number }, end: { X: number; Y: number }) {
  var _X = start.X - end.X
  var _Y = start.Y - end.Y
  return (360 * Math.atan(_Y / _X)) / (2 * Math.PI)
}
</script>

<style scoped lang="less">
.container {
  padding: 30rpx 32rpx 0;
  box-sizing: border-box;
  height: 100%;
  overflow: scroll;
  .recommendedChefs {
    margin-bottom: 16rpx;
    position: relative;
    display: flex;
    background: #fff;
  }
  .movable-area {
    width: 100%;
    height: 100rpx;
  }
  .movable-view {
    width: 100%;
    height: 100%;
  }
  .touch-item {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 100%;
    overflow: hidden;
    margin-bottom: 24rpx;
  }
  .touch-move-active .del {
    background-color: #ff4242;
  }

  .touch-move-active .content,
  .touch-move-active .del {
    -webkit-transform: translateX(0);
    transform: translateX(0);
  }
  .content {
    width: 100%;
    margin-right: 0;
    -webkit-transition: all 0.4s;
    transition: all 0.4s;
    -webkit-transform: translateX(120rpx);
    transform: translateX(120rpx);
    margin-left: -120rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 32rpx;
  }
  .content-box {
    display: flex;
    align-items: center;
  }
  .favorite-name {
    font-size: 32rpx;
  }
  .rename-icon {
    width: 30rpx;
    height: 30rpx;
    padding-left: 16rpx;
  }
  .favorite-operate {
    width: 20rpx;
    height: 40rpx;
    transform: rotate(180deg);
  }
  .del {
    background-color: #ff4242;
    width: 120rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    -webkit-transform: translateX(120rpx);
    transform: translateX(120rpx);
    -webkit-transition: all 0.4s;
    transition: all 0.4s;
    // border-top-right-radius: 20rpx;
    // border-bottom-right-radius: 20rpx;
  }
}
.btn {
  width: 100%;
  height: 88rpx;
  background-color: #333333;
  color: #fff;
  text-align: center;
  line-height: 88rpx;
  font-weight: 600;
  font-size: 32rpx;
}
</style>
